package demo_designPattern.factory.beanFactory;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;


public class Context implements BeanFactory{
	private Map<String, Object> container = new HashMap<String, Object>();

	public Context(String fileName) throws Exception {
		SAXBuilder sb = new SAXBuilder();
		Document doc = sb.build(this.getClass().getClassLoader()
				.getResourceAsStream(fileName));
		Element root = doc.getRootElement();
		List<?> list = XPath.selectNodes(root, "/beans/bean");
		for (int i = 0; i < list.size(); i++) {
			Element bean = (Element) list.get(i);
			String id = bean.getAttributeValue("id");
			String clazz = bean.getAttributeValue("class");
			Object o = Class.forName(clazz).newInstance();
			List<Element> children = (List<Element>)bean.getChildren();
			for(Element e : children){
				String propertyClazz = e.getAttributeValue("class");
				Object property = Class.forName(propertyClazz).newInstance();
				String name = e.getAttributeValue("name");
				Field field = o.getClass().getDeclaredField(name);
				field.setAccessible(true);
				field.set(o, property);
			}
			container.put(id, o);
		}

	}

	@Override
	public Object getBean(String id) {
		return container.get(id);
	}
}
